package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : xyiaao
 * @createDate : 2022/2/26 19:55
 */
@RestController
@RequestMapping("/sys_user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    /**
     * 系统设置 - 管理员管理
     * 用户列表 - 分页
     *
     * @param page
     * @param limit
     * @param loginName
     * @param status
     * @param phone
     * @return
     */
    @GetMapping("/list")
    public ResultData list(Integer page, Integer limit, @RequestParam("login_name") String loginName, Integer status, String phone) {

        Page<User> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(loginName), User::getLoginName, loginName);
        queryWrapper.eq(status != null, User::getStatus, status);
        queryWrapper.like(StringUtils.isNotEmpty(phone), User::getPhone, phone);
        userService.page(pageInfo, queryWrapper);
        Page<SysUserInfo> sysUserInfoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, sysUserInfoPage, "records");
        List<SysUserInfo> sysUserInfoList = pageInfo.getRecords().stream().map(user -> {
            SysUserInfo sysUserInfo = new SysUserInfo();
            BeanUtils.copyProperties(user, sysUserInfo);

            List<String> roleIdList = getStringRoleIds(user);
            sysUserInfo.setRoleIdList(roleIdList);

            //查询用户角色名称集合: roleNameList
            List<String> roleNameList = roleService.roleNameList(roleIdList);
            sysUserInfo.setRoleNameList(roleNameList);
            return sysUserInfo;
        }).collect(Collectors.toList());
        sysUserInfoPage.setRecords(sysUserInfoList);
        return ResultData.ok(PageResult.init(sysUserInfoPage));
    }

    /**
     * 将String转为roleIdList
     * @param user
     * @return
     */
    private List<String> getStringRoleIds(User user) {
        //查询用户角色id集合: roleIdList
        String[] roleIds = user.getRoleId().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> roleIdList = new ArrayList<>();
        Collections.addAll(roleIdList, roleIds);
        return roleIdList;
    }


    /**
     * 系统设置 - 管理员管理
     * 管理员删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(String id) {

        userService.removeById(id);
        return ResultData.ok("删除成功");
    }

    /**
     * 系统设置 - 管理员管理
     * 管理员添加
     *
     * @param sysUserInfo
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody SysUserInfo sysUserInfo) {

        getStringRoleIds(sysUserInfo);
        // 将用户密码进行md5加密
        sysUserInfo.setPassword(DigestUtils.md5Hex(sysUserInfo.getPassword()));
        userService.save(sysUserInfo);
        return ResultData.ok("添加成功");
    }


    /**
     * 系统设置 - 管理员管理
     * 管理员详情
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {

        User user = userService.getById(id);
        SysUserInfo sysUserInfo = new SysUserInfo();
        BeanUtils.copyProperties(user, sysUserInfo);
        sysUserInfo.setRoleIdList(getStringRoleIds(user));
        return ResultData.ok(sysUserInfo);
    }


    /**
     * 系统设置 - 管理员管理
     * 管理员修改
     *
     * @param sysUserInfo
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody SysUserInfo sysUserInfo) {

        if (sysUserInfo.getRoleIdList() != null) {
            getStringRoleIds(sysUserInfo);
        }
        userService.updateById(sysUserInfo);
        return ResultData.ok("修改成功");
    }

    /**
     * 将roleIdList转为String
     * @param sysUserInfo
     */
    private void getStringRoleIds(@RequestBody SysUserInfo sysUserInfo) {

        StringBuilder sb = new StringBuilder();
        List<String> roleIdList = sysUserInfo.getRoleIdList();
        sb.append("[");
        for (int i = 0; i < roleIdList.size(); i++) {
            String roleId = roleIdList.get(i);
            sb.append("\"").append(roleId).append("\"").append(i == roleIdList.size() - 1 ? "" : ",");
        }
        sb.append("]");
        sysUserInfo.setRoleId(sb.toString());
    }

}
